/**
 *    @file       udprecvthread.cpp
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       02/19/2014 02:17:43 PM
 *
 *    @author     Theophilus (), wangtf418@gmail.com
 */
#include "udprecvthread.h"

udprecvthread::udprecvthread(bf_uint32_t type, bf_uint32_t size, bf_uint32_t index, const comargs *args)
	: workthread(type, size, index, args)
{

}

udprecvthread::~udprecvthread()
{

}

bf_int_t udprecvthread::init()
{
	srv_socket_args *args = (srv_socket_args*)m_args;
	if (!args || !args->m_socket)
	{
		return BF_ERROR;
	}
	m_socket = args->m_socket;

	if (m_socket->get_socket() == INVALID_SOCKET)
	{
		bf_int_t ret = m_socket->socket(SOCK_DGRAM);
		if (ret != BF_OK)
		{
			return BF_ERROR;
		}

		m_socket->set_reuse_opt(true);
		ret = m_socket->bind();
		if (ret != BF_OK)
		{
			return BF_ERROR;
		}

		bf_int_t socket_buf_len = 8388608; //8MB
		m_socket->set_recvbuf_opt(socket_buf_len);
		m_socket->set_sendbuf_opt(socket_buf_len);
	}

	return BF_OK;
}

bf_int_t udprecvthread::run()
{
	init_run();

	bf_int_t recvlen = 0;
	while(m_runflag)
	{
		recvlen = m_socket->recvfrom(m_recvbuf, UDP_RECV_BUF_LEN, m_addr);
		if (recvlen > 0)
		{
			bf_char_t *buf = new bf_char_t[recvlen];
			addr_bufmsgbody *body = new addr_bufmsgbody(buf, recvlen, m_addr);
			send_msg(THD_TYPE_PROCESS, RAND_THD_INDEX, 0, MSG_TYPE_PROC, body);
		}
	}

	uninit_run();
	return BF_OK;
}

void udprecvthread::init_run()
{
	return;
}

void udprecvthread::uninit_run()
{
	return;
}

